import { useActiveThreadId } from "@renderer/queries/hooks/use-ui";
import type { Thread } from "@shared/triplit/types";
import { useCallback, useEffect, useState } from "react";

const { uiService, threadService } = window.service;

export function useActiveThread() {
  const { data: activeThreadId } = useActiveThreadId();

  const [selectedThread, setSelectedThread] = useState<Thread | null>(null);

  const setActiveThreadId = useCallback(async (threadId: string) => {
    await uiService.updateActiveThreadId(threadId || "");
  }, []);

  useEffect(() => {
    if (!activeThreadId) return;
    threadService.getThreadById(activeThreadId).then((thread) => {
      setSelectedThread(thread || null);
    });
  }, [activeThreadId]);

  return {
    activeThreadId,
    selectedThread,
    setActiveThreadId,
  };
}
